// backend/src/protocols/protobuf/index.js
const protobuf = require('protobufjs');
const logger = require('../../utils/logger');

class ProtobufManager {
    constructor() {
        this.root = null;
    }

    initialize(protoDefinitions) {
        try {
            // 直接使用已编译好的 protobuf 定义
            this.root = protobuf.Root.fromJSON(protoDefinitions);
            logger.info('Protobuf definitions loaded successfully');
            return true;
        } catch (error) {
            logger.error('Failed to initialize protobuf:', error);
            return false;
        }
    }

    encodeMessage(messageType, data) {
        try {
            // 使用完整的消息类型路径
            const MessageType = this.root.lookupType(`mstf.camb.proto.${messageType}`);
            if (!MessageType) {
                throw new Error(`Message type ${messageType} not found`);
            }

            // 创建消息并编码
            const message = MessageType.create(data);
            return MessageType.encode(message).finish();
        } catch (error) {
            logger.error(`Error encoding message ${messageType}:`, error);
            throw error;
        }
    }

    encodeRemoteXferMessage(messageType, payload) {
        try {
            const RemoteXferMessage = this.root.lookupType('mstf.camb.proto.RemoteXferMessage');
            const message = RemoteXferMessage.create({
                msgCnt: 1,
                version: "1.0",
                timeStamp: Math.floor(Date.now() / 1000),
                [this.getPayloadField(messageType)]: payload
            });

            return RemoteXferMessage.encode(message).finish();
        } catch (error) {
            logger.error('Error encoding RemoteXferMessage:', error);
            throw error;
        }
    }

    decodeMessage(buffer) {
        try {
            // 先解码为 RemoteXferMessage
            const RemoteXferMessage = this.root.lookupType('mstf.camb.proto.RemoteXferMessage');
            const message = RemoteXferMessage.decode(new Uint8Array(buffer));
            return this.processRemoteXferMessage(message);
        } catch (error) {
            logger.error('Error decoding message:', error);
            throw error;
        }
    }

    processRemoteXferMessage(message) {
        // 将 message 转换为普通对象
        const obj = message.toJSON();

        // 检查每个可能的payload字段
        const payloadFields = [
            'system_info_group',
            'periph_info_group',
            // 添加其他可能的payload字段
        ];

        for (const field of payloadFields) {
            if (obj[field]) {
                return {
                    type: this.getMessageType(field),
                    data: obj[field],
                    timestamp: obj.timeStamp,
                    version: obj.version
                };
            }
        }

        return null;
    }

    getPayloadField(messageType) {
        // 将 PascalCase 转换为 snake_case
        return messageType
            .replace(/\.?([A-Z])/g, (x,y) => "_" + y.toLowerCase())
            .replace(/^_/, "");
    }

    getMessageType(field) {
        // 将 snake_case 转换为 PascalCase
        return field
            .split('_')
            .map(part => part.charAt(0).toUpperCase() + part.slice(1))
            .join('');
    }
}

module.exports = new ProtobufManager();
